package com.agilerabbit.tools;

import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class RssParser extends XmlParserRobot {

	private final String TITLE = "title";
	private final String DESCRIPTION = "description";
	private final String LINK = "link";
	private final String PUBDATE = "pubDate";

	public List<Feed> GetFeeds(InputStream inputStream) {
		String xml = getXmlString(inputStream);
		return GetFeedsFromXmlString(xml);
	}

	public List<Feed> GetFeedsFromXmlString(String xml) {
		List<Feed> entries = new ArrayList<Feed>();
		Document doc = getDomElement(xml);
		NodeList nl = doc.getElementsByTagName("item");

		for (int i = 0; i < nl.getLength(); i++) {

			Element e = (Element) nl.item(i);
			String title = getNodeText(e, TITLE);
			String description = getNodeText(e, DESCRIPTION);
			String link = getNodeText(e, LINK);
			String pubDate = getNodeText(e, PUBDATE);
			Feed entry = new Feed(title, description, link);
			entry.pubdate = pubDate;
			// Thu, 15 Nov 2012 10:14:57 GMT
			SimpleDateFormat gmtFormat = new SimpleDateFormat(
					"EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
			gmtFormat.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
			try {

				Date date = gmtFormat.parse(pubDate);
				SimpleDateFormat df2 = new SimpleDateFormat(
						"dd-MMMM-yyyy HH:mm:ss");
				entry.pubdate = df2.format(date);

			} catch (ParseException e1) {
				// TODO Auto-generated catch block
				// e1.printStackTrace();
			}
			
			entries.add(entry);
		}

		return entries;
	}

	public List<Feed> GetFeeds(String RssUrl) {
		String xml = getXmlString(RssUrl);
		return GetFeedsFromXmlString(xml);
	}

}
